﻿/*
 * Create By:Jeff Yuan
 * Create Time : 2009-03-09 14:50
 * 用于查看 服务器信息 如：进程，系统，磁盘信息等
 * 
 */
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Diagnostics;
using System.Management;
using System.IO;
/// <summary>
///ProcessDataSource 的摘要说明
/// </summary>
public class SystemInfo
{
    private DataTable _processdatatable = null;
    private double _cpudata = 0.0;
    /// <summary>
    /// 在使用本数据前 请调用GenerateAllInfo
    /// 返回的数据表 列名:Name=进程名 User=进程的用户名 CPU=进程的CPU使用率 WorkingSet=内存使用
    /// </summary>
    public DataTable DataSource
    {
        get { return _processdatatable; }
        set { _processdatatable = value; }
    }
    /// <summary>
    /// 在使用本数据前 请调用GenerateAllInfo
    /// </summary>
    public string CpuUsePercent
    {
        get { return _cpudata.ToString("0.0") + "%"; }
    }
    /// <summary>
    /// 性能计数器，用于获取CPU空闲百分比
    /// </summary>
    private static PerformanceCounter mIdle = null;
    /// <summary>
    /// 性能计数器，用于获取CPU总利用率
    /// </summary>
    private static PerformanceCounter mTotal = null;
    /// <summary>
    /// 产生当前状态的进程与CPU使用率信息。 每次调用会更新。
    /// </summary>
    /// <returns></returns>
    public bool GenerateAllInfo()
    {
        if (mIdle == null) 
        mIdle = new PerformanceCounter("Process", "% Processor Time", "Idle");
        if (mTotal == null) 
        mTotal = new PerformanceCounter("Process", "% Processor Time", "_Total");
        double idlePercent = mIdle.NextValue(); // 空闲比率
        double totalPercent = mTotal.NextValue(); //总使用比率
        //初始化数据表
        if (_processdatatable == null)
        {
            _processdatatable = new DataTable();
            _processdatatable.Columns.Add("Name");
            _processdatatable.Columns.Add("User");
            _processdatatable.Columns.Add("CPU");
            _processdatatable.Columns.Add("WorkingSet");
        }
        _processdatatable.Rows.Clear(); //清除无用数据
        double cputotal = 0;//
        Process[] pos = Process.GetProcesses();
        foreach (Process p in pos)
        {
            try
            {
                string[] str = new string[4];
                str[0] = p.ProcessName;
                str[1] = this.GetProcessUser(p.Id);
                str[2] = p.TotalProcessorTime.TotalMilliseconds.ToString();
                cputotal += p.TotalProcessorTime.TotalMilliseconds; //计算总花费时间                
                str[3] = (p.WorkingSet64 / 1024).ToString() + " K";
                _processdatatable.Rows.Add(str);
            }
            catch
            {

            }
        }
        for (int i = 0; i < pos.Length ; i++ )
        {
            try
            {
                if (pos[i].Id == 0 || pos[i].HasExited)
                {
                    continue;
                }
                double cpuproc = 0; //该进程相关的时间花费
                if (double.TryParse(_processdatatable.Rows[i]["CPU"].ToString(), out cpuproc))
                {
                    _processdatatable.Rows[i]["CPU"] = (pos[i].TotalProcessorTime.TotalMilliseconds - cpuproc).ToString();
                }
                else
                {
                    return false;
                }
                cputotal -= pos[i].TotalProcessorTime.TotalMilliseconds; //计算单周期花费时间
            }
            catch
            {

            }

        }
        cputotal = -cputotal;
        for (int i = 0; i < _processdatatable.Rows.Count; i++)
        {
            double tmp=0;
            if(double.TryParse(_processdatatable.Rows[i]["CPU"].ToString(),out tmp)&&tmp!=0)
            {
                _processdatatable.Rows[i]["CPU"] = (Math.Abs(tmp / cputotal * 100)).ToString("0.0");
            }
        }
        System.Threading.Thread.Sleep(500);
        idlePercent = mIdle.NextValue(); 
        totalPercent = mTotal.NextValue();
        if (totalPercent == 0) //避免异常
        {
            _cpudata = 0;
        }
        else
        {
           // CPU利用率 =  (总使用率-空闲率) / 总使用率 
            _cpudata =100 * (totalPercent-idlePercent)/totalPercent;
        }
        return true;
    }

    public string GetOperator()
    {
        return Environment.OSVersion.ToString();
    }
    /// <summary>
    /// 返回的数据表 列名：DeviceID=驱动盘符名,Size=总容量,FreeSpace=空闲空间
    /// </summary>
    /// <returns></returns>
    public DataTable GetDiskInfo()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("DeviceID");
        dt.Columns.Add("Size");
        dt.Columns.Add("FreeSpace");
        SelectQuery selectQuery = new
         SelectQuery("Win32_LogicalDisk");
        ManagementObjectSearcher searcher =
            new ManagementObjectSearcher(selectQuery);
        foreach (ManagementObject disk in searcher.Get())
        {
            string[] str = new string[3];
            str[0] = disk["DeviceID"].ToString();
            try
            {
                UInt64 disksize = 0;
                if (UInt64.TryParse(disk["Size"].ToString(), out disksize))
                {
                    str[1] = (disksize / 1024 / 1024 /1024).ToString("0.0") + " GB";
                }
            }
            catch
            {
                str[1] = "未知";
            }
            try
            {
                UInt64 diskfreespace = 0;
                if (UInt64.TryParse(disk["FreeSpace"].ToString(), out diskfreespace))
                {
                    str[2] = (diskfreespace / 1024 / 1024 / 1024).ToString("0.0") + " GB";
                }
            }
            catch
            {
                str[2] = "未知";
            }
            dt.Rows.Add(str);
        }
        return dt;
    }
    /// <summary>
    /// 查询进程与CPU使用率信息 无比在构造后调用GenerateAllInfo()
    /// </summary>
    public SystemInfo()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }
    /// <summary>
    /// 查询某进程的所属用户
    /// </summary>
    /// <param name="processid"></param>
    /// <returns></returns>
    public string   GetProcessUser(int processid)
    {
        SelectQuery query1 = new SelectQuery("SELECT   *   FROM   Win32_Process WHERE ProcessID=" + processid.ToString());
        ManagementObjectSearcher searcher1 = new ManagementObjectSearcher(query1);
        foreach (ManagementObject mob in searcher1.Get())
        {
            if (mob["ProcessID"].ToString() == processid.ToString()) //
            {
                string[] obj = new string[2]; //GETOWNER方法需要2个参数
                object i = mob.InvokeMethod("GetOwner", (object[])obj);
                if (i.ToString() == "0") //查询成功的标识
                {
                   return obj[0].ToString();
                }
                else
                {
                   return "Unknown";
                }
            }
        }
        return "ERROR";
    }

}
